﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LightCAD.MathLib.CSG
{
   public class OffFile
    {
        public static RawMesh Read(string filename)
        {
            var mesh = new RawMesh();
            using (var sr = new StreamReader(filename))
            {

                if (sr.ReadLine() != "OFF")
                    throw new Exception("error format.");

                var nums = sr.ReadLine().Split(' ');
                var numVertices = int.Parse(nums[0]);
                var numFaces = int.Parse(nums[1]);
                var numEdges = int.Parse(nums[2]);

                for (var i = 0; i < numVertices; i++)
                {
                    var varr = sr.ReadLine().Split(' ');
                    var x = double.Parse(varr[0]);
                    var y = double.Parse(varr[1]);
                    var z = double.Parse(varr[2]);
                    mesh.vertices.Add(new CorkVertex(x, y, z));
                }
                for (var i = 0; i < numFaces; i++)
                {
                    var varr = sr.ReadLine().Split(' ');
                    var dim = int.Parse(varr[0]);
                    int a = 0, b = 0, c = 0;
                    if (dim >= 1)
                        a = int.Parse(varr[1]);
                    if (dim >= 2)
                        b = int.Parse(varr[2]);
                    if (dim >= 3)
                        c = int.Parse(varr[3]);
                    mesh.triangles.Add(new CorkTriangle(a, b, c));
                }

                return mesh;
            }
        }
        public static void Write(string filename, RawMesh mesh)
        {
            using (var sw = new StreamWriter(filename))
            {
                sw.WriteLine("OFF");
                sw.WriteLine($"{mesh.vertices.Count} {mesh.triangles.Count} {0}");

                for (var i = 0; i < mesh.vertices.Count; i++)
                {
                    var v = mesh.vertices[i];
                    sw.WriteLine($"{v.pos.x} {v.pos.y} {v.pos.z}");
                }
                for (var i = 0; i < mesh.triangles.Count; i++)
                {
                    var t = mesh.triangles[i];
                    sw.WriteLine($"{t.a} {t.b} {t.c}");
                }
            }
        }
    }
}
